import { createRouter, createWebHistory } from 'vue-router'
import { useSysStore } from '../stores/sys'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      name: "login",
      path: "/login",
      component: () => import('../views/login.vue')
    },
    {
      name: "index",
      path: "/",
      component: () => import('../views/index.vue'),
      children: [
        {
          name: "home",
          path: "/home",
          component: () => import('../views/home.vue')
        },
        {
          name: 'system',
          path: '/system',
          children: [
            {
              name: 'permission',
              path: '/system/permission',
              children: [
                {
                  name: 'role',
                  path: '/system/permission/role',
                  component: () => import('../views/system/permission/role/index.vue')
                },
                {
                  name: 'user',
                  path: '/system/permission/user',
                  component: () => import('../views/system/permission/user/index.vue')
                }
              ]
            },
          ]
        }
      ]
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue'),
    },

  ]
})
let isDer = false

router.beforeEach(async (to, from, next) => {
  // 检查是否访问登录页面
  if (to.path === '/login') {
    return next()
  }
  
  // 检查用户是否已登录（检查 sessionStorage 中是否有用户信息）
  const userStr = sessionStorage.getItem("user")
  const user = userStr ? JSON.parse(userStr) : null
  
  // 如果没有用户信息，重定向到登录页面
  if (!user) {
    ElMessage.warning('未登录或登录已过期，请重新登录')
    return next('/login')
  }

  const sysStore = useSysStore()
  if (!isDer) {
    await sysStore.loadPermissions()
    isDer = true
    if (from.path == "/login" || to.path == "/") {
      sysStore.switchActiveModule("home")
      return next({ path: "/home" })

    }
    sysStore.switchActiveModule(sysStore.getActiveModuleName)
    next({ path: to.path })

  }
  else {
    return next()
  }
})
export default router